//== GAIA ============================================================================

//== BEGINNING OF CODE ===============================================================

//#include "sagittarius/core/SagittariusCore.h"


#include <stdio.h>
#include <malloc.h>
#include <assert.h>
#include "sagittarius/parallel/atomics.h"
#include "sagittarius/parallel/futex.h"

//#define _GNU_SOURCE
#define __USE_GNU
#include <unistd.h>
#include <linux/futex.h>
#include <time.h>
#include <sys/time.h>
#include <sys/syscall.h>
#include <sched.h>
#include <errno.h>
//#include <sys/stat.h>
#include <fcntl.h>

int child = 0;
volatile int mytid = 0;
int futex = 1;
//struct timespec t = {0, 500000000}; //1/2 sec
struct timespec t = {0, 125000000}; //1/8 sec

int target() {
    //int fd=0;
    //sleep(1);
    //assert(0);
    child = 1;
    //if(child == 1)
    //fd = open("~/afile.txt", O_WRONLY);
    sg_write(2, "111Value of child is\n", sizeof("111Value of child is\n"));
    return 0;
    //_exit(0);
}

int main(int argc, char* argv[])
{
    //void* child_stack = malloc(4096);
    void** child_stack = (void **) malloc(16384);
    fflush(stdout);
    fflush(stderr);
    /*int res = syscall(SYS_clone,
          NULL, 
          0,
          //CLONE_THREAD|CLONE_VM|CLONE_FILES|CLONE_SIGHAND|CLONE_FS,
          //CLONE_VM|CLONE_FILES|CLONE_SIGHAND|CLONE_FS,
          CLONE_VM|CLONE_FILES,
          NULL //fn arg
    );*/
    int res = clone(
          target, 
          child_stack,
          //CLONE_THREAD|CLONE_VM|CLONE_FILES|CLONE_SIGHAND|CLONE_FS,
          //CLONE_VM|CLONE_FILES|CLONE_SIGHAND|CLONE_FS,
          CLONE_VM|CLONE_FILES,
          NULL //fn arg
    );
    //sleep(1);
    //wait_futex(&futex);
    //sg_fad32(&mytid, 1);
    //srand();
    //mytid = rand();
    //++mytid;
    
    syscall(SYS_nanosleep, &t, NULL);
    //fflush(stdout);
    //fflush(stderr);
    
    //printf("My thread id is %d\n", mytid);
    //fflush(stdout);
    //fflush(stderr);
    //printf("Value of childa is %d\n", child);
    //printf("Value of res is %d\n", res);
    //printf("errno = %d\n", errno);
    //if(child == 0)
    sg_write(2, "Value of child i2s ", sizeof("Value of child i2s "));
    sg_writeInt2(child);
    sg_write(2, "\n", 1);
    //fflush(stdout);
    //fflush(stderr);
    //free(child_stack);
    
    //finished_futex(&futex);
    //sleep(1);
    
    return 0;
}
